<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
$name_s=dirname(__FILE__);


$name=$_SERVER['DOCUMENT_ROOT']."think/simplewind/";
include_once($name."Lib/weixing/WxPay.Api.php");
include_once($name."Lib/weixing/WxPay.Notify.php");
include_once($name."Lib/weixing/log.php");
include_once($name_s."/connConfig.php");
include_once($name_s."/httpclient.php");
include_once($name_s."/mysql.class.php");
include_once($name_s."/redis.class.php");
include_once($name_s."/logger.php");


//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
//$logger =  new Logger("./logs/yj.log");
class PayNotifyCallBack extends WxPayNotify
{
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);
		Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}

	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{
        $this->SetReturn_code("SUCCESS");
        $this->SetReturn_msg("OK");
		error_log("$data" . "\n\r", 3, 'error_weixing.log');
        //$postObj = simplexml_load_string($postArr);
		Log::DEBUG("call back:" . json_encode($data));
		$notfiyOutput = array();

		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}

		error_log($data["transaction_id"] . "\n\r", 3, 'error_weixing.log');
        $transaction_id=$data["transaction_id"];
        $out_trade_no=$data["out_trade_no"];
        $openid=$data["openid"];
        $this->do_trade($transaction_id,$out_trade_no,$openid);
		return true;
	}



    function do_trade($transaction_id,$out_trade_no,$openid) {
        $redis = new RedisDriver();
        $mysql = new MysqlDriver();

        $this->connect_db($redis, $mysql,$userid);
        $row_ok = $mysql->select('applypay','*',array('iap_transaction_id' =>$transaction_id));
        if($row_ok){
            exit();
        }
        $row = $mysql->select('applypay','*',array('order_id' =>$out_trade_no));
        error_log(json_encode($row) . "\n\r", 3, 'error_weixing.log');

            $data = array(
                'is_send' => 1,
                'type' => 1,
                'iap_transaction_id'=>$transaction_id,
                'update_time' => date('Y-m-d H:i:s',time())
            );
            //$logger->info('applePayTrade', json_encode($data));
            //充值成功后改变状态；

            $mysql->update('applypay',$data,array('order_id' => $out_trade_no) );;



            //处理充值，加金币或道具
           // $goodsid=$goods[0]['id'];
            $goodsid=$row[0]['goods_id'];
            $uid=$row[0]['uid'];
            $redis->initDataRedis($uid);
            $player = $redis->data_redis->hMGet("hu:{$uid}", array('id','user','exp', 'name', 'money', 'coin','isget_coin_task_reward_record'));
            //var_dump($player);

            if($goodsid==7 && $player['isget_coin_task_reward_record']==1){
                exit("你已经购买过此商品,不可购买");
            }

            //处理充值，加金币或道具

            $goodsadd = $redis->cache_redis->hMGet("hg:{$goodsid}", array("money","rmb","propnum","give_money"));

            $add_coin = (int)($goodsadd['money']);

            if($goodsid>=20 && $goodsid<30){
                $type=1;
                $proop_info=add_porp($goodsid,$uid ,$redis,(int)$player['money'],(int)$goodsadd['give_money'],$mysql,(int)$goodsadd['rmb']);

            }

            if($goodsid>=30 && $goodsid<50){
                gift_pay($goodsid,$uid ,$redis,(int)$goodsadd['rmb'],$goodsadd['propnum']);
            }
            if($goodsid>=50){
                gift_money($goodsadd['give_money'],$mysql,$redis,$uid,$player['money'],(int)$goodsadd['rmb']);
            }

            if($goodsid<10){
                if($goodsid==7){
                    $exp=10;
                    $redis->data_redis->hSet("hu:{$uid}","isget_coin_task_reward_record",1);
                }else{
                    $exp=(int)$goodsadd['rmb'];
                }

                //给用户加钻石
                $cur_coin = $redis->data_redis->hincrBy("hu:{$uid}","coin",$add_coin);

                //给用户加经验
                $redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
                $ret=$redis->data_redis->hMget("hu:{$uid}",array("coin","money","exp"));
                $mysql->update('applypay',array('coin'=>$ret['coin'],'exp'=>$ret['exp']),array('order_id' => $out_trade_no) );;

                //var_dump($ret);
                //写入变化记录

                if($cur_coin){
                    $info =array();
                    $info['type'] = '6';
                    $info['uid']    = $uid;
                    $info['coin']  = $ret['coin'];
                    $info['change_coin'] = $add_coin;
                    $info['create_time']  = time();
                    $mysql->insert("coin_change_rec",$info);//写入金币变化表；
                }else{

                    $this->returnData(array(),588,'redis写入失败');
                }

            }


            //插入充值记录
            $pyinfo = array('uid'=>$uid,'rmb'=>$goodsadd['rmb'],'goodsid'=>$goodsid,'create_time'=>time(),'type'=>20);

            $mysql->insert('payrecord', $pyinfo);






        $num=$proop_info['num'];
        $prop_id=$proop_info['prop_id'];


        $http = new httpclient();
        if($goodsid<10){
            $type=2;
            $url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=PaySuccessResult&receiver='.$uid .'&param={"data_type":'.$type.',"data":{"coin":'.$ret['coin'].'}';
        }else{
            $url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=PaySuccessResult&receiver='.$uid .'&param={"data_type":'.$type.',"data":{"prop_num":'.$num.',"prop_id":'.$prop_id.'}}';

        }
        //echo $url;
        error_log("$url" . "\n\r", 3, 'error_weixing.log');

        if(!$http->Get($url)){

        }

        $http->close();
        $redis->deinitDataRedis();
        $redis->deinitCacheRedis();
        $mysql->close();
        //curl请求苹果app_store验证地址
    /*    $rmb=$goodsadd['rmb'];
        $url='http://dwc.gametu.com/think/index.php?g=Home&m=weixing&a=send_msg&id='.$uid.'&rmb='.$rmb.'&openid='.$openid.'';
        header("location:".$url);*/
        exit;

    }


    function connect_db(&$redis, &$mysql, $uid) {
        $ret = $mysql->connect(Config::$mysql_config);
        if (!$ret) {
            echo("mysql connect error.\n");
            exit(0);
        }

        $ret = $redis->initCacheRedis();
        if (!$ret) {
            echo("cache redis connect error.\n");
            exit(0);
        }

        $ret = $redis->initDataRedis($uid);
        if(!$ret) {
            echo("data redis connect error.\n");
            exit(0);
        }
    }



}

Log::DEBUG("begin notify");

error_log("4545454545" . "\n\r", 3, 'error_weixing.log');
$notify = new PayNotifyCallBack();
//$notify->do_trade();
$notify->Handle(false);
